package com.ocl.www.controller;

import com.ocl.www.basic.BasicController;
import com.ocl.www.domain.Lyarticle;
import com.ocl.www.service.LyArticleService;
import com.ocl.www.utils.RedisUtil;
import net.sf.json.JSONArray;
import org.apache.commons.net.ntp.TimeStamp;
import org.apache.log4j.Logger;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.cache.ehcache.EhCacheManager;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import sun.misc.BASE64Encoder;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.sql.SQLException;
import java.util.*;

/**
 * Created by Administrator on 2017/5/28.
 */
@RestController
@RequestMapping("/file")
public class FileController extends BasicController {

    @Autowired
    private LyArticleService lyArticleService;
    @Autowired
    private EhCacheManager em;

    private Logger logger = Logger.getLogger(FileController.class);

    /**
     * @Method: makeFileName
     * @Description: 生成上传文件的文件名，文件名以：uuid+"_"+文件的原始名称
     * @Anthor:孤傲苍狼
     * @param filename 文件的原始名称
     * @return uuid+"_"+文件的原始名称
     */
    private String makeFileName(String filename){  //2.jpg
        //为防止文件覆盖的现象发生，要为上传文件产生一个唯一的文件名
        return UUID.randomUUID().toString() + "_" + filename;
    }
    //文件上传相关代码

    @RequestMapping(value = "/upload", method = RequestMethod.POST )
    public @ResponseBody
    Map<String,String> upload(@RequestParam("file") MultipartFile file, HttpServletRequest request, HttpServletResponse response) {

        Map<String,String> fileinfo = new HashMap<String,String>();
        //得到上传文件的保存目录，将上传的文件存放于WEB-INF目录下，不允许外界直接访问，保证上传文件的安全
//        String savePath = request.getServletContext().getRealPath(File.separator+"upload");
        String savePath = request.getServletContext().getRealPath("/WEB-INF/classes/public/");
        //上传时生成的临时文件保存目录
//        String tempPath = request.getContextPath();

        if (file.isEmpty()) {
            fileinfo.put("status","e");
            fileinfo.put("info","file is empty");

            return fileinfo;
        }
        // 获取文件名
        String fileName = makeFileName(String.valueOf(new TimeStamp(new Date().getTime())));
        logger.info("上传的文件名为：" + fileName);

        // 获取文件的后缀名
        String suffixName = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."));
        logger.info("上传的后缀名为：" + suffixName);

        // 文件上传后的路径
        StringBuilder filePath = new StringBuilder();
        filePath.append(savePath).append("upload").append(File.separator);
        logger.info(filePath.toString());

        // 解决中文问题，liunx下中文路径，图片显示问题
        // fileName = UUID.randomUUID() + suffixName;
        StringBuilder fileAllPath = new StringBuilder();
        fileAllPath.append(filePath).append(fileName).append(suffixName);
        File dest = new File(fileAllPath.toString());
        // 检测是否存在目录
        if (!dest.getParentFile().exists()) {
            dest.getParentFile().mkdirs();
        }
        try {
            file.transferTo(dest);
            fileinfo.put("status","s");
            fileinfo.put("info","file upload succ");
            fileinfo.put("address",File.separator+"upload"+File.separator+fileName + suffixName);
        } catch (IllegalStateException e) {
            fileinfo.put("status","e");
            fileinfo.put("info",e.getMessage());
        } catch (IOException e) {
            fileinfo.put("status","e");
            fileinfo.put("info",e.getMessage());
        }
        return fileinfo;
    }



    @RequestMapping(value="/wordInfo", method=RequestMethod.POST)
    public @ResponseBody Map<String ,String> wordInfo(@RequestParam("hasName") String hasName,@RequestParam("imgAddr") String imgAddr, @RequestParam("msg") String msg){
        Map<String,String> maptemp = new HashMap<>();

        if (imgAddr.isEmpty()||imgAddr==null||imgAddr==""){
            maptemp.put("status","e");
            maptemp.put("info","图片不能为空！");
            return maptemp;
        }

        Lyarticle lyarticle = new Lyarticle();
        if ("1".equals(hasName)){
            lyarticle.setUserId(SecurityUtils.getSubject().getPrincipal().toString());
        }else{
            lyarticle.setUserId("匿名的狼");
        }
        lyarticle.setPicPath(imgAddr);
        lyarticle.setPicWord(msg);
        int c=0;
        try {
            c = lyArticleService.insertlyArticle(lyarticle);
            maptemp.put("status","s");
            maptemp.put("info","");

//            redis缓存
//            Jedis redis = RedisUtil.getJedis();
//            redis.del("com.ocl.www.service.LyArticleServiceselectlyArticleList");
//            RedisUtil.returnResource(redis);

        } catch (Exception e) {
            maptemp.put("status","e");
            maptemp.put("info",e.getMessage());
        }
        return maptemp;
    }

    @RequestMapping(value="/selectAll", method=RequestMethod.POST)
    public @ResponseBody Map<String,String> selectAll(HttpServletRequest request){
        Map<String,String> map = new HashMap<>();

        List<Lyarticle> lyarticleList = null;
        try {
            lyarticleList = lyArticleService.selectlyArticleList();

            String path = null;
            StringBuilder picPath =  new StringBuilder();
            // 获取文件的后缀名
            String suffixName = null;
            StringBuilder sb = new StringBuilder();

            for (int i=0;i<lyarticleList.size();i++){
                path = request.getServletContext().getRealPath("/");
                picPath.append(path).append("WEB-INF").append(File.separator).append("classes").append(File.separator).append("public");
                logger.info(picPath);
                // 获取文件的后缀名
                suffixName = picPath.substring(picPath.lastIndexOf(".")+1);

                sb.append("data:image/").append(suffixName).append(";base64,").append(GetImageStr(picPath+lyarticleList.get(i).getPicPath()));
                lyarticleList.get(i).setPicPath(sb.toString());

            }
            map.put("status","s");
            map.put("info", JSONArray.fromObject(lyarticleList).toString());

//            map.put("lylist",lyarticleList);

        } catch (Exception e) {
            e.printStackTrace();
            map.put("status","e");
            map.put("info",e.getMessage());
        }
        return map;
    }

    public static String GetImageStr(String picPath) {
        //将图片文件转化为字节数组字符串，并对其进行Base64编码处理
        //String imgFile = "d://test.jpg";//待处理的图片
        String imgFile = picPath;//待处理的图片
        InputStream in = null;
        byte[] data = null;
        //读取图片字节数组
        try{
            in = new FileInputStream(imgFile);
            data = new byte[in.available()];
            in.read(data);
            in.close();
        }catch (IOException e){
        //  e.printStackTrace();
        }
        //对字节数组Base64编码
        BASE64Encoder encoder = new BASE64Encoder();
        try {
            String str = encoder.encode(data);//返回Base64编码过的字节数组字符串
            return str;
        }catch (java.lang.NullPointerException e){
            return "";
        }

    }
}
